<template>
  <div class="goodsDetailIndex">
    <div class="titleBar">
      <div class="backIcon" @click="back"></div>
      <div class="shareIcon" v-if="goodsDetail.title || goodsDetail.desc" @click="shareGoods"></div>
    </div>
    <div class="Wrap" ref="indexScroll">
      <div class="scrollWrap">
        <div class="banner-wrapper">
          <div class="slide-banner-scroll" ref="imgSlide">
            <div class="slide-banner-wrapper">
              <div class="slide-item" v-for="(n, i) in goodsDetail.thumb_list" :key="i">
                <img :src="n.path" alt="">
              </div>
            </div>
          </div>
          <div v-if="limit === 'true' || limit === true">
            <div class="time" v-if="goodsDetail.flag !== 'end'">
              <p v-if="goodsDetail.flag === 'runing'">距离活动结束：{{ timeObj && timeObj.days + ' 天 ' + timeObj.hours + ' 时 ' + timeObj.minutes + ' 分 ' + timeObj.seconds + ' 秒 '}}</p>
              <p v-if="goodsDetail.flag === 'no-start'">距离活动开始：{{ timeObj && timeObj.days + ' 天 ' + timeObj.hours + ' 时 ' + timeObj.minutes + ' 分 ' + timeObj.seconds + ' 秒 '}}</p>
            </div>
          </div>
          <div class="docs-wrapper">
            <span
              class="doc"
              v-for="(item, index) in goodsDetail.thumb_list"
              :key="index"
              :class="{'active': currentPageIndex === index}"></span>
          </div>
        </div>
        <div class="goodsDetail">
          <div class="price">
            <div class="nowPrice">{{goodsDetail.price}}颜值</div>
            <div class="oldPrice">原价：{{goodsDetail.old_price}}</div>
          </div>
          <div class="goodsName">
            {{goodsDetail.title}}
          </div>
          <div class="desc">
            {{goodsDetail.desc}}
          </div>
        </div>
        <div class="goodsShowWrap">
          <div class="goodsShow">
            <div class="showTitle">
              <div class="line lineLeft"></div>
              <div class="title">宝贝展示</div>
              <div class="line lineRight"></div>
            </div>
            <div class="goodsInfo" v-resize="scrollRefresh" v-html="goodsDetail.content">
              
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="buyBtn" :class="{noStart: goodsDetail.flag && goodsDetail.flag !== 'runing'}" @click="buyThis">
      立即兑换
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'
BScroll.use(Slide)
export default {
  name: 'YanZhiGoodsDetail',
  data() {
    return {
      scroll: null,
      slide: null,
      currentPageIndex: 0,
      playTimer: 0,
      goodsDetail: {},
      timer: null,
      timeObj:null,
      limit: false,
      id: '',
      token: ''
    };
  },
  async mounted () {
    this.token = sessionStorage.getItem('token')
    this.id = this.$route.query.id
    this.limit = this.$route.query.limit
    this.getGoodsDetail()
  },
  directives: {  // 使用局部注册指令的方式
    resize: { // 指令的名称
      bind(el, binding) { // el为绑定的元素，binding为绑定给指令的对象
        let width = '', height = '';
        function isReize() {
          const style = document.defaultView.getComputedStyle(el);
          if (width !== style.width || height !== style.height) {
            binding.value();  // 关键
          }
          width = style.width;
          height = style.height;
        }
        el.__vueSetInterval__ = setInterval(isReize, 300);
      },
      unbind(el) {
        clearInterval(el.__vueSetInterval__);
      }
    }
  },
  methods: {
    buyThis () {
      if (this.goodsDetail.flag === 'no-start') {
        this.$toastMessage({message: '限时抢购商品未开启，您可以先兑换其他商品哦'})
        return
      }
      if (this.goodsDetail.flag === 'end') {
        this.$toastMessage({message: '限时抢购商品已结束，您可以兑换其他商品哦'})
        return
      }
      this.$router.push({path: 'orderDetail', query: {id: this.id}})
    },
    back () {
      this.$router.go(-1)
    },
    shareGoods () {
      window.WebViewJavascriptBridge.callHandler('shareGoods', {
        goodsId: this.id,
        title: this.goodsDetail.title,
        desc: this.goodsDetail.desc,
        thumb: this.goodsDetail.thumb
      }, () => {

      })
    },
    async getGoodsDetail () {
      await this.$axios.get("https://kotest.bojem.com/user/goodsDetails", {
        params: {
          id: this.id,
          token: this.token
        }
      })
      .then(res => {
        console.log(res)
        if (res.status === 200) {
          if (res.data.code === '0000') {
            this.goodsDetail = res.data.data
            if (res.data.data.time > 0) {
              this.timeObj = this.calcDate(this.goodsDetail.time);
              this.countDown()
            }
            if (res.data.data.thumb_list.length > 0) {
              this.$nextTick(() => {
                this.imgSlideInit()
              })
            }
            this.$nextTick(() => {
              this.scrollInit()
            })
          } else {
            if (res.data.msg) {
              throw new Error(res.data.msg)
            } else {
              throw new Error('请求异常')
            }
          }
        } else {
          throw new Error('网络错误')
        }
      })
      .catch((error) => {
        this.$toastMessage({message: error.message})
      });
    },
    scrollInit () {
      this.scroll = new BScroll(this.$refs.indexScroll, {
        scrollX: false,
        scrollY: true,
        click: true,
      })
    },
    scrollRefresh () {
      this.scroll.refresh()
    },
    imgSlideInit () {
      clearTimeout(this.playTimer)
      this.slide = new BScroll(this.$refs.imgSlide, {
        scrollX: true,
        scrollY: false,
        slide: {
          loop: true,
          threshold: 100
        },
        momentum: false,
        bounce: false,
        stopPropagation: true
      })
      this.slide.on('scrollEnd', this._onScrollEnd)
      // user touches the slide area
      this.slide.on('beforeScrollStart', () => {
        clearTimeout(this.playTimer)
      })
      // user touched the slide done
      this.slide.on('scrollEnd', () => {
        this.autoGoNext()
      })
      this.slide.on('slideWillChange', (page) => {
        this.currentPageIndex = page.pageX
      })
      this.autoGoNext()
    },
    nextPage() {
      this.slide.next()
    },
    autoGoNext() {
      clearTimeout(this.playTimer)
      this.playTimer = setTimeout(() => {
        this.nextPage()
      }, 4000)
    },
    calcDate(diff){
      const diffDuration = moment.duration(diff, 'seconds');
      if (diff <= 0){
        console.log('倒计时结束')
        this.getGoodsDetail()
      }
      let self = this;
      let days = parseInt(diffDuration.asDays(), 10)
      let hours = parseInt(diffDuration.asHours(), 10)
      if (hours > 23) {
        hours = hours - days * 24
      }
      console.log(hours)
      let minutes = (parseInt(diffDuration.asMinutes()) % 60)
      let seconds = parseInt(diffDuration.asSeconds()) % 60
      let m = {
          diff:diff,//时间戳
          days: `${days}`,
          hours: `${hours === 24 ? '00' : (hours < 10 ? '0' + hours : hours)}`,
          minutes: `${minutes < 10 ? '0' + minutes : minutes}`,
          seconds: `${seconds < 10 ? '0' + seconds : seconds}`,
          toString: function() { 
            return self.isShowDays ? `${this.days} ${this.hours}:${this.minutes}:${this.seconds}` :`${this.hours}:${this.minutes}:${this.seconds}`
          }
      };
      console.log(m)
      return m;
    },
    formatTime(unix){
      var t = null;
      var d = null;
      var h = null;
      var m = null;
      var s = null;
      //js默认时间戳为毫秒,需要转化成秒  / 1000;
      t = unix
      // d = Math.floor(t / (24 * 3600));
      d = Math.floor(t / (24 * 3600));
      h = Math.floor((t-24 * 3600 * d) / 3600);
      m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
      s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60));

      h = h <10? `0${h}` : `${h}`;
      m = m <10? `0${m}`:`${m}`;
      s = s<10? `0${s}`: `${s}`;
      d = d < 1?`0${d}`:`${d}`;
      return {d,h,m,s}
    },
    countDown(){
      clearInterval(this.timer)
      this.timer = setInterval(()=>{
        this.timeObj.diff -= 1;
        let obj = this.formatTime(this.timeObj.diff)
        this.timeObj.days = obj.d;
        this.timeObj.hours = obj.h;
        this.timeObj.minutes = obj.m;
        this.timeObj.seconds = obj.s;
        if(this.timeObj.diff <= 0) {
          this.getGoodsDetail()
          clearInterval(this.timer)
        }
      },1000)
    }
  }
};
</script>
<style lang="stylus">
  .goodsDetailIndex
    width 100%
    height calc(100vh - constant(safe-area-inset-top))
    height calc(100vh - env(safe-area-inset-top))
    position relative
    padding-top 44px
    padding-top  constant(safe-area-inset-top); /* 兼容 iOS < 11.2 */
    padding-top: env(safe-area-inset-top);
    .titleBar{
      height 1rem
      padding 0 0.3rem 0
      background transparent
      padding-top  constant(safe-area-inset-top); /* 兼容 iOS < 11.2 */
      padding-top: env(safe-area-inset-top);
      display flex
      justify-content space-between
      align-items center
      position absolute
      top  constant(safe-area-inset-top); /* 兼容 iOS < 11.2 */
      top: env(safe-area-inset-top);
      left 0
      right 0
      z-index 100
      .backIcon{
        width 0.6rem
        height 0.6rem
        background url(../../assets/images/backIcon.png) no-repeat
        background-size contain
      }
      .shareIcon{
        width 0.6rem
        height 0.6rem
        background url(../../assets/images/shareIcon.png) no-repeat
        background-size contain
      }
    }
    .Wrap
      height 100vh
      overflow hidden
      .banner-wrapper
        position relative
        height 8.6rem
        background #fff
        .slide-banner-scroll
          min-height 1px
          overflow hidden
        .slide-banner-wrapper
          height 8rem
          white-space nowrap
          font-size 0
          .slide-item
            display inline-block
            height 8rem
            width 100%
            line-height 8rem
            text-align center
            font-size 26px

            img{
              width 100%
              height 100%
            }
      .time
        position absolute
        bottom 0.6rem
        width 100%
        height 0.75rem
        background rgba(0, 0, 0, 0.7)
        p
          font-size 0.26rem
          color #eeeeee
          line-height 0.75rem
          margin 0
          padding 0 0.3rem
      .docs-wrapper
        display flex
        position absolute
        bottom 4px
        left 50%
        transform translateX(-50%)
        .doc
          display inline-block
          margin 0 4px
          width 8px
          height 8px
          border-radius 50%
          background #CCCCCC
        .active
          width 20px
          border-radius 5px
          background #7B2D3E

      .goodsDetail{
        padding 0.4rem 0.3rem
        background #fff
        
        .price{
          display flex;
          align-items center
          .nowPrice{
            font-size: 0.4rem;
            color: #383838;
            margin-right 0.2rem
          }
          .oldPrice{
            font-size: 0.24rem;
            color: #999
            text-decoration: line-through;
          }
        }
        .goodsName{
          font-size 0.3rem
          color #383838
          margin 0.3rem 0 0.16rem
          display -webkit-box
          /* autoprefixer: off */
          -webkit-box-orient vertical
          /* autoprefixer: on */
          -webkit-line-clamp 2
          text-overflow ellipsis
          overflow hidden
        }
        .desc{
          font-size 0.26rem
          color #999999
          line-height 0.4rem
        }
      }
      .goodsShowWrap{
        padding-top: 0.2rem
        background: #F5F5F5
      }
      .goodsShow{
        padding 0.5rem 0.3rem
        background #fff
        padding-bottom 1.8rem

        .showTitle{
          display flex
          justify-content center
          align-items center
          .title{
            font-size 0.3rem
            color #000
            margin 0 0.2rem
            user-select:none;
          }
          .line{
            width 1.2rem
            height 0.02rem
          }
          .lineLeft{
            background: -moz-linear-gradient(left, #FFFFFF 0%, #CCCCCC 100%)
            background: -webkit-gradient(linear, left left, left right, color-stop(0%,#FFFFFF), color-stop(100%,#CCCCCC))
            background: -webkit-linear-gradient(left, #FFFFFF 0%, #CCCCCC 100%)
            background: -o-linear-gradient(left, #FFFFFF 0%, #CCCCCC 100%)
            background: -ms-linear-gradient(left, #FFFFFF 0%, #CCCCCC 100%)
            background: linear-gradient(to right, #FFFFFF 0%, #CCCCCC 100%)
          }
          .lineRight{
            background: -moz-linear-gradient(left, #CCCCCC 0%, #FFFFFF 100%)
            background: -webkit-gradient(linear, left left, left right, color-stop(0%,#CCCCCC), color-stop(100%,#FFFFFF))
            background: -webkit-linear-gradient(left, #CCCCCC 0%, #FFFFFF 100%)
            background: -o-linear-gradient(left, #CCCCCC 0%, #FFFFFF 100%)
            background: -ms-linear-gradient(left, #CCCCCC 0%, #FFFFFF 100%)
            background: linear-gradient(to right, #CCCCCC 0%, #FFFFFF 100%)
          }
        }
        .goodsInfo{
          margin-top 0.3rem
          p{
            margin 0
          }
          img{
            width 100% !important
          }
        }
        .goodsInfo img{
          width 100%
        }
      }
    .buyBtn{
      position fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1.1rem
      background: #7B2C3F
      font-size: 0.3rem
      line-height: 1.1rem
      text-align: center
      color: #fff
    }
    .noStart{
      background #898788
    }
</style>
